import requests
import time
from hashlib import md5
import requests, json
from work.models import *
import unittest
from django.http import JsonResponse


api_key = 'API_KEY'
api_secret = 'wasd1230'


def create_sign(api_key, api_secret, timestamp):
    """
       创建签名的方法, 用apikey, api_secret, timestamp进行md5加密
       :param api_key
       :param api_secret
       :param timestamp
       :return:
       """
    data = api_key + api_secret + timestamp
    system_sign = md5(data.encode('utf-8')).hexdigest()
    return system_sign


# 验证签名身份
def verify_sign(api_key, api_secret, timestamp, sign):
    timestamp = timestamp
    api_key = api_key
    api_secret = api_secret
    real_sign = create_sign(api_key, api_secret, timestamp)
    if real_sign == sign:
        result = True
    else:
        result = False
    return result



def send_orders(username, orders, passcode):
    """
    {
    "timestamp": "时间戳",
    "api_key": "",
    "sign": "签名",
    "username": "用户账号",
    "orders": [商品编码],
    "data": "订单编号"
}
    """
    timestamp = str(int(time.time()))
    sign = create_sign(api_key, api_secret, timestamp)
    user_name = username
    # 存放商品码
    # orders = ["11111", "22222", "33333", "44444"]
    orders = orders
    # 存放订单编号
    # data = '20200430'
    data = passcode
    url = "http://127.0.0.1:8000/api/orders/add_orders/"
    data_dict = {"timestamp": timestamp, "api_key": api_key, "sign": sign, "username": user_name,
            "orders": orders, "data": data}

    data_json = json.dumps(data_dict)

    headers = {'Content-Type': 'application/json'}

    s = requests.session()
    response = s.post(url=url, headers=headers, data=data_json)
    return response


# 接收拍摄系统返回状态
def receive_shooting_status(request):
    """
    用于接收拍摄系统返回对应的商品码的拍摄完成状态
    {"timestamp":"132456789","api_key":"api_key","sign":"sign",
    "data":[{"code":"1111","shooting_status":1,"shooting_finished_date":"2020-05-01"},
    {"code":"2222","shooting_finished_date":"2020-05-01"}]}
    :param request:
    :return:
    """
    if request.method == "POST":
        # 获取json数据
        json_str = request.body
        json_str = json_str.decode()
        req_data = json.loads(json_str)
        api_key = req_data["api_key"]
        timestamp = req_data["timestamp"]
        sign = req_data["sign"]
        # 进行身份验证
        if verify_sign(api_key, api_secret, timestamp, sign):
            added_count = 0
            failed_messages = []
            data_list = req_data["data"]
            for data in data_list:
                code = data["code"]
                # shooting_status = data["shooting_status"]
                shooting_finished_date = data["shooting_finished_date"]
                good = Goods.objects.filter(code=code).first()
                if good:
                    good.shooting_status = 1
                    good.shooting_finished_date = shooting_finished_date
                    good.save()
                    added_count += 1
                else:
                    failed_messages.append({
                        "code": code,
                        "detail": "此商品码错误"
                    })
            data = {"success": True, "success_count": added_count, "error": failed_messages}
            return JsonResponse(data)
        else:
            data = {"success": False, "data": {"msg": "身份验证失败！"}}
            return JsonResponse(data)